extends VBoxContainer

@onready var _projectNameInput:LineEdit = $"ProjectId/LineEdit"
@onready var _deleteBtn:Button = $"ProjectId/DeleteButton"
@onready var _pathLabel = $"PathLabel"

var _old_project_name = ""

func _ready():
	_deleteBtn.button_down.connect(_on_button_down_deleteBtn)
	_projectNameInput.focus_exited.connect(_on_focus_exited_projectNameInput)


func _on_button_down_deleteBtn():
	var project_name = _projectNameInput.text
	Global.remove_project(project_name)
	queue_free()
	
	
func _on_focus_exited_projectNameInput():
	var new_project_name = _projectNameInput.text
	Global.rename_project(_old_project_name, new_project_name)
	_old_project_name = new_project_name
	
	
func _on_text_changed_savePathInput():
	var project_name = _projectNameInput.text
	var new_path = _pathLabel.text
	Global.update_save_path(project_name, new_path)


func refresh(project_name):
	_projectNameInput.text = project_name
	_pathLabel.text = ""
	
	var config_data = Global.config_datas.get(project_name)
	if config_data != null:
		_pathLabel.text = config_data.save_path
		
	_old_project_name = project_name


func _on_select_path_button_button_down() -> void:
	var defaultFolderPath = _pathLabel.text
	DisplayServer.file_dialog_show("选择版本文件保存路径", defaultFolderPath, "", true, DisplayServer.FILE_DIALOG_MODE_OPEN_DIR, [], _on_select_folder_finished)
	

func _on_select_folder_finished(status:bool, paths, index):
	if paths.size() <= 0:
		return
	var path = paths[0]
	path = path.replace("\\", "/")
	_pathLabel.text = path
	Global.update_save_path(_projectNameInput.text, _pathLabel.text)
